<?php

namespace App\Http\Controllers;

use App\Http\Controllers\Controller;
use QCloud\COSSTS\Sts;
use Illuminate\Http\Request;
use Illuminate\Support\Facades\Storage;

class UploadController extends Controller
{
    public function getToken(Request $Request){
        $id = env('UPLOAD_APP_ID');
        $key = env('UPLOAD_APP_KEY');
        
        $sts = new Sts();
        $config = array(
            'url' => 'https://sts.tencentcloudapi.com/', // url和domain保持一致
            'domain' => 'sts.tencentcloudapi.com', // 域名，非必须，默认为 sts.tencentcloudapi.com
            'proxy' => '',
            'secretId' => $id, // 固定密钥,若为明文密钥，请直接以'xxx'形式填入，不要填写到getenv()函数中
            'secretKey' => $key, // 固定密钥,若为明文密钥，请直接以'xxx'形式填入，不要填写到getenv()函数中
            'bucket' => 'xinzhu-1301398555', // 换成你的 bucket
            'region' => 'ap-shanghai', // 换成 bucket 所在园区
            'durationSeconds' => 1800, // 密钥有效期
            'allowPrefix' => array('*'), // 这里改成允许的路径前缀，可以根据自己网站的用户登录态判断允许上传的具体路径，例子： a.jpg 或者 a/* 或者 * (使用通配符*存在重大安全风险, 请谨慎评估使用)
            // 密钥的权限列表。简单上传和分片需要以下的权限，其他权限列表请看 https://cloud.tencent.com/document/product/436/31923
            'allowActions' => array (
                // 简单上传
                'name/cos:PutObject',
                'name/cos:PostObject',
                // 分片上传
                'name/cos:InitiateMultipartUpload',
                'name/cos:ListMultipartUploads',
                'name/cos:ListParts',
                'name/cos:UploadPart',
                'name/cos:CompleteMultipartUpload'
            ),
            // 临时密钥生效条件，关于condition的详细设置规则和COS支持的condition类型可以参考 https://cloud.tencent.com/document/product/436/71306
            // "condition" => array(
            //     "ip_equal" => array(
            //         "qcs:ip" => array(
            //             "10.217.182.3/24",
            //             "111.21.33.72/24",
            //         )
            //     )
            // )
        );
        
        // 获取临时密钥，计算签名
        $tempKeys = $sts->getTempKeys($config);
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$tempKeys]);
    }

    public function WxAppOneLoad(Request $Request){
        if(!$Request->fileurl){
            return response()->json(['code' => '403', 'msg' => '请选择文件']);
        }
        $secretId = env('UPLOAD_APP_ID'); //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretKey = env('UPLOAD_APP_KEY'); //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $region = "ap-shanghai"; //替换为用户的 region，已创建桶归属的 region 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $cosClient = new \Qcloud\Cos\Client(
            array( 'region' => $region, 'schema' => 'https', 'credentials'=> array( 'secretId'  => $secretId , 'secretKey' => $secretKey))
        );

        $key_upload = $Request->key ? $Request->key : 'user';
        $binaryData = base64_decode($Request->fileurl);
        $tmpfname = tempnam(sys_get_temp_dir(), 'base64');
        file_put_contents($tmpfname, $binaryData);
        $filename = uniqid().'-'.time() . '.png'; // 生成文件名
        try {
            $bucket = "xinzhu-1301398555";
            $key = 'wxapp/'.$key_upload.'/'.$filename; //此处的 key 为对象键，对象键是对象在存储桶中的唯一标识
            $file = fopen($tmpfname, 'rb');
            if ($file) {
                $result = $cosClient->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'Body' => $file));
                    $res = 'https://'.$result['Location'];
            }
        } catch (\Exception $e) {
            echo "$e\n";
        }
        return response()->json(['code' => 200, 'data' => $res]);
    }

    public function WxAppLoad(Request $Request){
        if(!$Request->source){
            return response()->json(['code' => '403', 'msg' => '请选择文件']);
        }
        $secretId = env('UPLOAD_APP_ID'); //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretKey = env('UPLOAD_APP_KEY'); //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $region = "ap-shanghai"; //替换为用户的 region，已创建桶归属的 region 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $cosClient = new \Qcloud\Cos\Client(
            array( 'region' => $region, 'schema' => 'https', 'credentials'=> array( 'secretId'  => $secretId , 'secretKey' => $secretKey))
        );

        $source = $Request->source;
        $key_upload = $Request->key ? $Request->key : 'user';
        $arr = [];
        foreach ($source as $k => $value) {
            // $v_ = explode('?',$value);
            // $extension = pathinfo($v_[0], PATHINFO_EXTENSION);
            // $imageContent = file_get_contents($value['path']);
            $binaryData = base64_decode($value['path']);
            $tmpfname = tempnam(sys_get_temp_dir(), 'base64');
            file_put_contents($tmpfname, $binaryData);
            $filename = uniqid().'-'.time() . '.png'; // 生成文件名
            try {
                $bucket = "xinzhu-1301398555";
                $key = 'wxapp/'+$key_upload+'/'.$filename; //此处的 key 为对象键，对象键是对象在存储桶中的唯一标识
                $file = fopen($tmpfname, 'rb');
                if ($file) {
                    $result = $cosClient->putObject(array(
                        'Bucket' => $bucket,
                        'Key' => $key,
                        'Body' => $file));
                    $arr[$k] = 'https://'.$result['Location'];
                }
            } catch (\Exception $e) {
                echo "$e\n";
            }
        }
        return response()->json(['code' => 200, 'data' => $arr]);
    }

    public function XiuMiImgLoad(Request $Request){
        if(!$Request->source){
            return response()->json(['code' => '403', 'msg' => '请选择文件']);
        }
        $secretId = env('UPLOAD_APP_ID'); //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretKey = env('UPLOAD_APP_KEY'); //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $region = "ap-shanghai"; //替换为用户的 region，已创建桶归属的 region 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $cosClient = new \Qcloud\Cos\Client(
            array( 'region' => $region, 'schema' => 'https', 'credentials'=> array( 'secretId'  => $secretId , 'secretKey' => $secretKey))
        );

        $source = $Request->source;
        $arr = [];
        foreach ($source as $k => $value) {
            $v_ = explode('?',$value);
            $extension = pathinfo($v_[0], PATHINFO_EXTENSION);
            $imageContent = file_get_contents($value);
            if ($imageContent) {
                $filename = uniqid().'-'.time() . '.'.$extension; // 生成文件名
                try {
                    $bucket = "xinzhu-1301398555";
                    $key = 'xiumi/'.$filename; //此处的 key 为对象键，对象键是对象在存储桶中的唯一标识
                    $file = $imageContent;
                    if ($file) {
                        $result = $cosClient->putObject(array(
                            'Bucket' => $bucket,
                            'Key' => $key,
                            'Body' => $file));
                        $arr[$k] = 'https://'.$result['Location'];
                    }
                } catch (\Exception $e) {
                    echo "$e\n";
                }
            }else{
                return response()->json(['code' => '403', 'msg' => '无法访问或获取图像。']);
            }
        }
        return response()->json(['code' => 200, 'data' => $arr]);
    }

    public function getVideoToken(Request $Request){
        $key = 'Xr4A9BYZaR6bu780WwFammiVA5qRuEvU';
        $id = 'AKID0sbCcVFrMk294rTwELFyVGqDh5cw40pT';
        $current = time();
        $expired = $current + 86400;  // 签名有效期：1天


        // 向参数列表填入参数
        $arg_list = array(
            "secretId" => $id,
            "currentTimeStamp" => $current,
            "expireTime" => $expired,
            "random" => rand()
        );

        // 计算签名
        $original = http_build_query($arg_list);
        $signature = base64_encode(hash_hmac('SHA1', $original, $key, true).$original);
        return response()->json(['code' => '200', 'msg' => 'success','data'=>$signature]);
    }

    public function index(Request $Request){
        
        if(!$Request->file('file')){
            return response()->json(['code' => '403', 'msg' => '请选择文件']);
        }

        $filename = $Request->file('file')->getClientOriginalName();
        $filename = explode('.',$filename);
        $filename_exp = $filename[1];
        $data = $Request->file('file')->storeAs ('nodes',Date("YmdHis",time()).'.'.$filename_exp,['disk' => 'public_uploads']);
        return response()->json(['code' => '200', 'msg' => 'success','data'=>env('APIURL').'/'.$data]);
    }

    public function XiuMiImg(Request $Request){
        
        if(!$Request->source){
            return response()->json(['code' => '403', 'msg' => '请选择文件']);
        }
        $source = $Request->source;
        $arr = [];
        foreach ($source as $key => $value) {
            $v_ = explode('?',$value);
            $extension = pathinfo($v_[0], PATHINFO_EXTENSION);
            $imageContent = file_get_contents($value);
            if ($imageContent) {
                $filename = uniqid().'-'.time() . '.'.$extension; // 生成文件名（这里假设为JPEG格式）
                    // 将图像内容写入新文件
                if (file_put_contents(public_path('wxappImage/' . $filename), $imageContent)) {
                    // 如果需要返回图像路径，则可以使用以下代码
                    $savedImagePath = asset('/wxappImage/' . $filename);
                    $arr[$key] = $savedImagePath;
                }
            }else{
                return response()->json(['code' => '403', 'msg' => '无法访问或获取图像。']);
            }
        }
        return response()->json(['code' => 200, 'data' => $arr]);
    }


    public function upLoadFIle(Request $Request){
        if(!$Request->fileurl){
            return response()->json(['code' => '403', 'msg' => '请选择文件']);
        }
        $secretId = env('UPLOAD_APP_ID'); //替换为用户的 secretId，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $secretKey = env('UPLOAD_APP_KEY'); //替换为用户的 secretKey，请登录访问管理控制台进行查看和管理，https://console.cloud.tencent.com/cam/capi
        $region = "ap-shanghai"; //替换为用户的 region，已创建桶归属的 region 可以在控制台查看，https://console.cloud.tencent.com/cos5/bucket
        $cosClient = new \Qcloud\Cos\Client(
            array( 'region' => $region, 'schema' => 'https', 'credentials'=> array( 'secretId'  => $secretId , 'secretKey' => $secretKey))
        );

        $key_upload = $Request->key ? $Request->key : 'user';
        $binaryData = base64_decode($Request->fileurl);
        $tmpfname = tempnam(sys_get_temp_dir(), 'base64');
        file_put_contents($tmpfname, $binaryData);
        $filename = uniqid().'-'.time() . '.png'; // 生成文件名
        try {
            $bucket = "xinzhu-1301398555";
            $key = 'wxapp/'.$key_upload.'/'.$filename; //此处的 key 为对象键，对象键是对象在存储桶中的唯一标识
            $file = fopen($tmpfname, 'rb');
            if ($file) {
                $result = $cosClient->putObject(array(
                    'Bucket' => $bucket,
                    'Key' => $key,
                    'Body' => $file));
                    $res = 'https://'.$result['Location'];
            }
        } catch (\Exception $e) {
            echo "$e\n";
        }
        return response()->json(['code' => 200, 'data' => $res]);
    }

}
